<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2018/4/28 16:47
 */


namespace App\Http\Controllers;


use App\Models\Client;
use GuzzleHttp\Client as QueryBase;
use Illuminate\Http\Request;

class MiniController extends Controller
{
    /**
     * 获取token
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getToken(Request $request)
    {
        $code = $request->input('code');
        $queryBase = new QueryBase();
        $req = $queryBase->request('GET','https://api.weixin.qq.com/sns/jscode2session',[
            'query' => [
                'appid' => env('APP_ID'),
                'secret' => env('APP_SECRET'),
                'js_code' => $code,
                'grant_type' => 'authorization_code'
            ]
        ]);
        $result = json_decode($req->getBody());

        $clientObj = Client::query()->firstOrCreate(['open_id' => $result->openid]);
        $token = md5($result->openid.$result->session_key);
        $clientObj->token = $token;
        $clientObj->save();
        return response()->json(['r' => 1000, 'i' => $token]);
    }

    public function test(Request $request)
    {
        return response()->json(['r' => 1000, 'i' => 'test']);
    }
}